﻿using Bird.Core.Domain.Members;
using Bird.Services.Members;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
namespace Bird.Services.Authentication
{
    public class FormsAuthenticationService : IAuthenticationService
    {

        Member _cachedMember;

        HttpContextBase _httpContext;
        IMemberService _memberService;

        public FormsAuthenticationService(HttpContextBase httpContext, IMemberService memberService)
        {
            _httpContext = httpContext;
            _memberService = memberService;
        }

        public void SignIn(Core.Domain.Members.Member member, bool remember)
        {
            DateTime now = DateTime.UtcNow.ToLocalTime();
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                member.Username, now, now.Add(FormsAuthentication.Timeout),
                remember,
                member.Email, FormsAuthentication.FormsCookiePath);
            string encrypted = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                encrypted);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent)
                cookie.Expires = ticket.Expiration;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
                cookie.Domain = FormsAuthentication.CookieDomain;
            _httpContext.Response.Cookies.Add(cookie);
            _cachedMember = member;
        }

        public void SignOut()
        {
            _cachedMember = null;
            FormsAuthentication.SignOut();
        }

        public Core.Domain.Members.Member GetAuthenticatedMember()
        {
            if (_cachedMember != null)
                return _cachedMember;
            if (_httpContext == null || _httpContext.Request == null
                || !_httpContext.Request.IsAuthenticated ||
                !(_httpContext.User.Identity is FormsIdentity))
                return null;
            FormsIdentity identity = (FormsIdentity)_httpContext.User.Identity;
            Member member = GetMemberFromTicket(identity.Ticket);
            if (member != null && member.Active)
                _cachedMember = member;
            return _cachedMember;
        }

        public virtual Member GetMemberFromTicket(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
                return null;
            string username = ticket.Name;
            if (string.IsNullOrWhiteSpace(username))
                return null;
            Member member = _memberService.GetMemberByUsernameOrEmail(username);
            return member;
        }
    }
}
